<?php
header("Content-Type: text/html;charset=utf-8");
include_once('config/config.php');
if ($_GET) {
  $getParams = $_GET;
  $sql = 'SELECT * FROM `admin` WHERE `id` = ' . $getParams['id'] . '';
  $getData = dbFind($sql);
}
// pre($getData);


if ($_POST) {
  $params = $_POST;

  $action = $_POST['action'];
  if ($action == 'checkName') {
    $username = $_POST['username'];
    if (empty(trim($username))) {
      error('用户名不能为空');
    }
    $id = $_POST['id'];
    $allName = dbAll("SELECT `username` FROM `admin` WHERE `id` <> '$id '");
    foreach ($allName as $item) {
      if ($username == $item['username']) {
        error('用户名已存在');
        break;
      }
    }
    success('用户名可以使用');
  }

  //封装更新数组
  $data = [
    'username' => $params['username']
  ];

  if ($params['pass']) {
    if (empty($params['password'])) {
      ShowMsg('新密码不能为空');
      exit;
    }
    if (empty($params['repassword'])) {
      ShowMsg('确认新密码不能为空');
      exit;
    }

    $pass = md5($params['pass'] . $getData['salt']);
    if ($pass != $getData['password']) {
      ShowMsg('密码错误');
      exit;
    }
    //密码盐
    $salt = build_ranstr();
    $data['salt'] = $salt;
    $data['password'] = md5($params['password'] . $salt);
  }
  if ($_FILES['avatar'] && $_FILES['avatar']['size'] > 0) {
    $avatar = upload('avatar');
    $data['avatar'] = $avatar['data'];
  }

  //更新新数据到数据库
  $sqlWhere = '`id` = ' . $getParams['id'];
  $res = dbUpdate('admin', $data, $sqlWhere);
  if ($res) {
    if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
      @is_file($getData['avatar']) && @unlink($getData['avatar']);
    }
    ShowMsg('更新成功', 'adminList.php');
    exit;
  } else {
    @is_file($data['avatar']) && @unlink($data['avatar']);
    ShowMsg('更新失败');
    exit;
  }

  exit;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
  <title>管理员</title>
  <!-- 引用公共头部 -->
  <?php include_once('common/meta.php'); ?>

  <style>
    #avatar {
      width: 200px;
      user-select: none;
    }

    #img {
      width: 200px;
      display: block;
    }

    .icon-list {
      margin-right: 5px;
    }
  </style>
</head>

<body>

  <!-- 引用公共头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 引用侧边菜单 -->
  <?php include_once('common/sidebar.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">修改管理员信息</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">首页</a> <span class="divider">/</span></li>
      <li class="active">管理员</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary " onClick="location='adminList.php'"><i class="icon-list"></i>管理员</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="POST" enctype="multipart/form-data">
                <?php
                $str = <<<LABEL
                <label>用户名</label>
                <input type="text" value="{$getData['username']}" class="input-xxlarge" name="username" >
                <span id="username" style="margin-left: 10px;"></span>

                <label>原密码</label>
                <input type="password" value="" class="input-xxlarge" name="pass" >

                <label>新密码</label>
                <input type="password" value="" class="input-xxlarge" name="password" >

                <label>确认新密码</label>
                <input type="password" value="" class="input-xxlarge" name="repassword" >

                <label>头像</label>
                <input type="file" value="" class="input-xxlarge" id="avatar" name="avatar" hidden>
                <label class="avatar" for="avatar">
                  <img src="{$getData['avatar']}" id="img">
                  <!-- <button class="btn btn-primary" type="button">选择文件</button> -->
                </label>
LABEL;
                echo $str;
                ?>

                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引用公共底部 -->
        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>
</body>

</html>
<!-- 引用script -->
<?php include_once('common/script.php'); ?>
<script>
  // 图片预览函数
  function GetObjectURL(file) {
    // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
    var url = null;

    //判断是否为IE浏览器还是google还是其他浏览器
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }

    return url
  }
  $('#avatar').change(function() {

    // 获取选中的文件
    let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};


    // 获取文件地址
    let url = GetObjectURL(file)
    $('#img').attr('src', url);
  });

  $('input[name="username"]').change(function() {
    let username = $(this).val();

    $.ajax({
      type: 'post',
      url: 'adminEdit.php',
      data: {
        id: <?php echo $getParams['id']; ?>,
        username,
        action: 'checkName'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#username').html(res.msg).css({
            "color": "green"
          })
        } else {
          $('#username').html(res.msg).css({
            "color": "red"
          })
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });
</script>